package com.yhy.recommend.listener;

import com.alibaba.fastjson.JSON;
import com.yhy.domain.mongo.PublishScore;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RocketMQMessageListener(
        topic = "tanhua-quanziR",
        consumerGroup = "tanhua-quanziR-consumer"
)
public class PublishScoreListener implements RocketMQListener<String> {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void onMessage(String message) {
//        1.解析传递过来的json
        Map<String, String> map = JSON.parseObject(message, Map.class);
//        2.构造传递数据(1.userId,2.type,3.唯一数字Id:pid)
        Long userId = Long.valueOf(map.get("userId"));
        Integer type = Integer.valueOf(map.get("type"));
        Long publishId = Long.valueOf(map.get("publishId"));
//        3.根据不同的操作类型传递不同的分数
        Double score = 0d;
        switch (type) {
            case 1: {
                score = 1d;
                break;
            }
            case 2: {
                score = 5d;
                break;
            }
            case 3: {
                score = 8d;
                break;
            }
            case 4: {
                score = 10d;
                break;
            }
            case 5: {
                score = -5d;
                break;
            }
            case 6: {
                score = -8d;
                break;
            }
            default: {
                break;
            }
        }
//        4.构造publishScore 返回mongoDB
        PublishScore ps = new PublishScore();
        ps.setId(ObjectId.get());
        ps.setUserId(userId);
        ps.setPublishId(publishId);
        ps.setDate(System.currentTimeMillis());
        ps.setScore(score);
        mongoTemplate.save(ps);
    }
}
